package com.wjy.common.authentication.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjy.common.authentication.user.entity.UserToken;
import com.wjy.common.authentication.user.mapper.UserTokenMapper;
import org.springframework.security.web.authentication.rememberme.PersistentRememberMeToken;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ybxxszl
 * @since 2019-04-12
 */
@Service
public class UserTokenServiceImpl extends ServiceImpl<UserTokenMapper, UserToken> implements PersistentTokenRepository {

    @Override
    public void createNewToken(PersistentRememberMeToken token) {
        UserToken userToken = new UserToken(token.getSeries(), token.getUsername(), token.getTokenValue(), token.getDate());
        save(userToken);
    }

    @Override
    public void updateToken(String series, String tokenValue, Date lastUsed) {
        UserToken userToken = new UserToken(series, tokenValue, lastUsed);
        updateById(userToken);
    }

    @Override
    public void removeUserTokens(String username) {
        Map<String, Object> columnMap = new HashMap<String, Object>();
        columnMap.put("username", username);
        removeByMap(columnMap);
    }

    @Override
    public PersistentRememberMeToken getTokenForSeries(String seriesId) {
        UserToken userToken = getById(seriesId);
        PersistentRememberMeToken token = new PersistentRememberMeToken(userToken.getUsername(), userToken.getUserTokenId(), userToken.getToken(), userToken.getLastUseTime());
        return token;
    }

}
